<?php
namespace backend\controllers;

use Yii;
use yii\helpers\Html;
use yii\data\ActiveDataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use backend\models\NewsNom;
use backend\models\NewsBanner;
use backend\models\NewsTag;
use backend\models\NewsTagRela;
use common\models\User;
use yii\web\Response;
use common\helpers\StringHelper;

class NewsnomController extends Controller
{
    public $enableCsrfValidation = false;

    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['index', 'banner','viewbefore','viewiframe', 'ueditor','has-list-banner','ajax-put-banner','ajax-delete-banner','add-new','ajax-get-news', 'create-banner', 'update-banner', 'create', 'view', 'update', 'upload','ueditor','crop','delete'],
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                ],
            ],
        ];
    }
    public function actions(){
        return [
            'ueditor'=>[
                'class' => 'common\widgets\ueditor\UeditorAction',
                'config'=>[
                    //上传图片配置
                    'imageUrlPrefix' => "http://image.bbeats.io/", /* 图片访问路径前缀 */
                    'imagePathFormat' => "uploads/news/", /* 上传保存路径,可以自定义保存路径和文件名格式 */
                ]
            ],
            'crop'=>[
                'class' => 'common\widgets\avatar\CropAction',
                'config'=>[
                    'bigImageWidth' => '2500',     //大图默认宽度
                    'bigImageHeight' => '1500',    //大图默认高度
                    'middleImageWidth'=> '400',   //中图默认宽度
                    'middleImageHeight'=> '220',  //中图图默认高度
                    'smallImageWidth' => '50',    //小图默认宽度
                    'smallImageHeight' => '50',   //小图默认高度
                    //头像上传目录（注：目录前不能加"/"）
                    'uploadPath' => 'uploads/news',
                ]
            ]
        ];
    }

    public function actionIndex()
    {
        $types = array(
            'all' => NewsNom::NEWS_STATUS_ALL,
            'draft' => NewsNom::NEWS_STATUS_DRA,
            'published' => [NewsNom::NEWS_STATUS_NOM, NewsNom::NEWS_STATUS_WAT],
            'recycle' => NewsNom::NEWS_STATUS_DEL
        );
        $active = Yii::$app->request->get("active",'all');
        $active = in_array($active,array_keys($types)) ? $active : 'all';

        $buld = NewsNom::find();
        if( $active != 'all' ) $buld = $buld->where(['status' => $types[$active]]);

        $dataProvider = new ActiveDataProvider([
            'query' => $buld->orderBy(['id' => SORT_DESC]),
        ]);
        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'active' => $active
        ]);
    }

    public function actionBanner(){
        $types = array(
            'all' => NewsNom::NEWS_STATUS_ALL,
            'draft' => NewsNom::NEWS_STATUS_DRA,
            'published' => [NewsNom::NEWS_STATUS_NOM, NewsNom::NEWS_STATUS_WAT],
            'recycle' => NewsNom::NEWS_STATUS_DEL
        );
        $active = Yii::$app->request->get("active",'published');
        $active = in_array($active,array_keys($types)) ? $active : 'published';

        $buld = NewsBanner::find()->where(['status' => $types[$active]])->orderBy(['sort' => SORT_ASC,'id' => SORT_DESC])->asArray()->all();
        

        return $this->render('banner', [
            'banner' => $buld,
            'active' => $active
        ]);
    }

    public function actionHasListBanner(){
        $num = NewsBanner::find()->where(['status' => 0,'position' => 1])->count();

        return $num;
    }

    public function actionCreateBanner(){
        $model = new NewsBanner();
        $user = Yii::$app->user->identity;
        $post = Yii::$app->request->post();

        if ($model->load($post) && $model->validate()) {
            $model->userid = $user->id;
            $model->ptime = $model->status == NewsNom::NEWS_STATUS_WAT ? $model->ptime : date("Y-m-d H:i:s",time());
            $model->ctime = time();
            $model->mtime = time();
            $model->save(false);
            return $this->redirect(['banner', 'id' => $model->id]);
        } else {
            return $this->render('createbanner', [
                'model' => $model,
            ]);
        }
    }

    public function actionUpdateBanner($id)
    {
        $model = NewsBanner::findOne($id);
        $user = Yii::$app->user->identity;
        $post = Yii::$app->request->post();
        if ($model->load($post) && $model->validate()) {
            $model->userid = $user->id;
            $model->ptime = $model->status == NewsNom::NEWS_STATUS_WAT ? $model->ptime : date("Y-m-d H:i:s",time());
            $model->mtime = time();
            $model->save(false);
            return $this->redirect(['banner', 'id' => $model->id]);
        } else {
            return $this->render('updatebanner', [
                'model' => $model,
            ]);
        }
    }

    public function actionAjaxGetNews(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $newsurl = Yii::$app->request->post("newsurl");

        $temp = explode("/",$newsurl);
        $file = explode(".",$temp[count($temp) - 1]);
        $file = explode("-",$file[0]);
        $newsid = $file[1];
        if( is_numeric($newsid) ){
            $model = $this->findModel($newsid);
            return ['ret' => true,'data' => $model];
        }else{
            return ['ret' => false,'data' => null];
        }
    }

    public function actionAjaxPutBanner(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $user = Yii::$app->user->identity;
        $banner = Yii::$app->request->post("banner");
        foreach ( $banner as $sort => $id ){
            NewsBanner::updateAll(['sort' => $sort],['id' => $id]);
        }

        return ['ret' => true];
    }

    public function actionAjaxDeleteBanner(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $user = Yii::$app->user->identity;
        $bannerid = Yii::$app->request->post("bannerid");
        NewsBanner::updateAll(['status' => 1],['id' => $bannerid]);

        return ['ret' => true];
    }

    public function actionAddNew(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $dataid = Yii::$app->request->get("data-id");

        if( Yii::$app->request->isPost ){
            $dataid = Yii::$app->request->post("dataid");
            $postid = Yii::$app->request->post("postid");
            $postid = trim($postid);

            print_r($postid);exit;
            $url = "content/posts/{$postid}";
            $data = $this->curlGet($url);

            return [
                'ret' => true,
                'data' => $data['content'],
                'dataid' => $dataid,
                'content' => $this->renderAjax('_bannerone',['item' => $data['content']])
            ];
        }else{
            return [
                'title' => StringHelper::truncateMsg("Add new banner", 160),
                'content' => $this->renderAjax('addnewbanner',['dataid' => $dataid]),
                'footer' => Html::button('save', ['class' => 'btn btn-default pull-right save']).
                    Html::button('close', ['class' => 'btn btn-default pull-left close', 'data-dismiss' => "modal"])
            ];
        }

    }

    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    public function actionCreate()
    {
        $model = new NewsNom();
        $user = Yii::$app->user->identity;
        $post = Yii::$app->request->post();
        $users = User::find()->orderBy('`id` <> '.$user->id.',id desc')->asArray()->all();
        $usermaps = yii\helpers\ArrayHelper::map($users,'id','username');

        if ($model->load($post) && $model->validate()) {
            if( $model->status == NewsNom::NEWS_STATUS_WAT ){
                if( strtotime($model->ptime) <= time() ){
                    return false;
                }
            }
            $model->authorname = $usermaps[$model->authorid];
            $model->userid = $user->id;
            $model->username = $user->username;
            $model->ptime = $model->status == NewsNom::NEWS_STATUS_WAT ? $model->ptime : date("Y-m-d H:i:s",time());
            $model->ctime = time();
            $model->mtime = time();
            $model->save(false);

            $this->saveTags($model->id,$model->tags);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
                'usermaps' => $usermaps,
            ]);
        }
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);
        $user = Yii::$app->user->identity;
        $post = Yii::$app->request->post();
        $users = User::find()->orderBy('`id` <> '.$user->id.',id desc')->asArray()->all();
        $usermaps = yii\helpers\ArrayHelper::map($users,'id','username');

        if ($model->load($post) && $model->validate()) {
            if( $model->status == NewsNom::NEWS_STATUS_WAT ){
                if( strtotime($model->ptime) <= time() ){
                    return $this->render('update', [
                        'model' => $model,
                        'msg' => '请正确填写发布时间'
                    ]);
                }
            }
            $model->userid = $user->id;
            $model->username = $user->username;
            $model->ptime = $model->status == NewsNom::NEWS_STATUS_WAT ? $model->ptime : date("Y-m-d H:i:s",time());
            $model->mtime = time();
            $model->save(false);

            $this->saveTags($model->id,$model->tags);
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
                'usermaps' => $usermaps,
            ]);
        }
    }

    public function actionViewiframe(){
        $this->layout = "main-single";
        $newsid = Yii::$app->request->get("id",0);
        $type = Yii::$app->request->get("type");

        if( $newsid ){
            $model = $this->findModel($newsid);
        }else{
            $model = new NewsNom();
        }

        return $this->render('viewiframe', ['type' => $type,'news' => $model]);
    }
    public function actionViewbefore(){
        Yii::$app->response->format = Response::FORMAT_JSON;
        $newsid = Yii::$app->request->get("data-id");
        $type = Yii::$app->request->get("type");

        return [
            'title' => StringHelper::truncateMsg("viewbefore", 160),
            'content' => $this->renderAjax('viewbefore',['newsid' => $newsid,'type' => $type]),
            'footer' => Html::button('close', ['class' => 'btn btn-default pull-right close','data-dismiss' => "modal"]).
                Html::button('close', ['class' => 'btn btn-default pull-left close', 'data-dismiss' => "modal"])
        ];
    }

    private function saveTags( $newsid, $tags ){
        if( !$newsid ) return false;

        $tag_arr = explode(",",$tags);
        if( empty($tag_arr) ){
            NewsTagRela::deleteAll(['newsid' => $newsid]);
        }else{
            $tagsids = array();
            foreach ( $tag_arr as $value ){
                $name = trim($value);
                $tagmodel = NewsTag::find()->where(['name' => $name])->one();
                $tagsids[] = $tagmodel->id;
            }

            $model = NewsTagRela::find()->where(['newsid' => $newsid])->andWhere(['not in','tagid',$tagsids])->one();
            $model && $model->delete();
        }

        foreach ( $tag_arr as $value ){
            $name = trim($value);
            $tagmodel = NewsTag::find()->where(['name' => $name])->one();

            if( !$tagmodel ){
                $tagmodel = new NewsTag();
                $tagmodel->name = $name;
                $tagmodel->save();
            }

            if( $tagmodel->id ){
                $newstagmodel = NewsTagRela::find()->where(['newsid' => $newsid,'tagid' => $tagmodel->id])->one();

                if( !$newstagmodel ){
                    $newstagmodel = new NewsTagRela();
                    $newstagmodel->newsid = $newsid;
                    $newstagmodel->tagid = $tagmodel->id;
                    $newstagmodel->tagname = $name;
                    $newstagmodel->save();
                }
            }
        }
    }

    public function actionDelete($id)
    {
        NewsNom::updateAll(['status' => 1],['id' => $id]);
        return $this->redirect(['index']);
    }

    /**
     * 返回格式参见
     */
    public function actionUpload()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        //TODO FileUpload
    }

    protected function findModel($id)
    {
        if (($model = NewsNom::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('您请求的页面不存在');
        }
    }
}
